#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 11/13/2019 6:26 PM
import traceback

from .base import BasePlugin
from lib.response import BaseResponse
from lib.log import logger
import settings


class Cpu(BasePlugin):
    def process(self, hostname, ssh_func):
        """
        执行命令，取硬盘信息
        :param hostname: host ip
        :param ssh_func:
        :return:
        """
        info = BaseResponse()
        try:
            if settings.DEBUG:
                with open('files/cpuinfo.out', mode='r', encoding='utf-8') as f:
                    content = f.read()
            else:
                content = ssh_func(hostname, 'cat /proc/cpuinfo')
            data = self.parse(content)
            info.data = data
        except Exception as e:
            msg = traceback.format_exc()
            logger.log(msg)
            info.status = False
            info.error = msg
        return info.dict

    def parse(self, content):
        """
        解析shell命令返回结果
        :param content: shell 命令结果
        :return:解析后的结果
        """
        response = {'cpu_count': 0, 'cpu_physical_count': 0, 'cpu_model': ''}

        cpu_physical_set = set()

        content = content.strip()
        for item in content.split('\n\n'):
            for row_line in item.split('\n'):
                value_list = row_line.split(':')
                if len(value_list) != 2:
                    continue
                key, value = value_list
                key = key.strip()
                if key == 'processor':
                    response['cpu_count'] += 1
                elif key == 'physical id':
                    cpu_physical_set.add(value)
                elif key == 'model name':
                    if not response['cpu_model']:
                        response['cpu_model'] = value
        response['cpu_physical_count'] = len(cpu_physical_set)

        return response
